/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.commons.domain;

import com.google.gson.JsonArray;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jety.commons.exception.JsonRpcRemoteException;
import org.jety.commons.util.JsonConverter;
import org.jety.commons.util.JsonRpcConstants;
import org.jety.server.AsynchronousTransport;

/**
 *
 * @author Rivaldo
 */
public class JsonRpcMethod {

    private static final Pattern METHOD_PATTERN = Pattern.compile("([_a-zA-Z][_a-zA-Z0-9]*)\\.([_a-zA-Z][_a-zA-Z0-9]*)");

    private int requestID;

    private JsonArray params = null;
    private String methodName = null;
    private String handleName = null;

    public JsonRpcMethod(int requestID, String requestMethodName, JsonArray params) throws JsonRpcRemoteException {
        this.requestID = requestID;
        this.params = params != null ? params : new JsonArray();
        separateName(requestMethodName);
    }

    private void separateName(String methodName) throws JsonRpcRemoteException {

        Matcher mat = METHOD_PATTERN.matcher(methodName);

        if (!mat.find()) {
            throw invalidMethodException();
        }

        this.handleName = mat.group(1);
        this.methodName = mat.group(2);
    }

    public boolean canExecute(Method method) {
        return method.getParameterTypes().length == params.size();
    }

    public int getRequestID() {
        return requestID;
    }

    public JsonArray getParams() {
        return params;
    }

    public Object[] getTypedParams(Method method) {
        return JsonConverter.convertParameters(method, params);
    }

    public String getMethodName() {
        return methodName;
    }

    public String getHandleName() {
        return handleName;
    }

    public Object[] getAsynchronousParams(Method method, AsynchronousTransport transport) {
        return JsonConverter.convertAsynchronousParameters(requestID, method, params, transport);
    }

    private JsonRpcRemoteException invalidMethodException() {
        int errorCode = JsonRpcConstants.INVALID_REQUEST_ERROR_CODE;
        String errorMessage = "Invalid method name";
        return new JsonRpcRemoteException(errorCode, errorMessage);
    }
}
